import 'dart:io';

class TranslationService {
  static Map<String, String> _dictionary = {};
  
  static Future<void> initialize() async {
    try {
      final file = File('assets/CET4_edited.txt');
      final lines = await file.readAsLines();
      
      for (var line in lines) {
        if (line.trim().isEmpty || !line.contains(' ')) continue;
        final parts = line.split(' ');
        if (parts.length >= 3) {
          final word = parts[0].toLowerCase();
          // 获取中文释义（第三列及之后的所有内容）
          final translation = parts.sublist(2).join(' ');
          _dictionary[word] = translation;
        }
      }
      print('Dictionary loaded with ${_dictionary.length} entries');
    } catch (e) {
      print('Error loading dictionary: $e');
    }
  }
  
  static String? getTranslation(String word) {
    return _dictionary[word.toLowerCase()];
  }
  
  static String? getCurrentWordTranslation(String text, int currentIndex) {
    if (text.isEmpty || currentIndex < 0 || currentIndex >= text.length) {
      return null;
    }
    
    // 找到当前单词的起始和结束位置
    int start = currentIndex;
    while (start > 0 && text[start - 1].trim().isNotEmpty) {
      start--;
    }
    
    int end = currentIndex;
    while (end < text.length && text[end].trim().isNotEmpty) {
      end++;
    }
    
    if (start == end) return null;
    
    final currentWord = text.substring(start, end).trim().toLowerCase();
    return getTranslation(currentWord);
  }
} 